package com.egoo.ticket.server.controller;

import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.egoo.ticket.server.dao.EwsUserDao;
import com.egoo.ticket.server.dao.WorkOrderDao;
import com.egoo.ticket.server.pojo.dto.SysOptLogDto;
import com.egoo.ticket.server.pojo.dto.WorkOrderExcelInput;
import com.egoo.ticket.server.pojo.dto.WorkOrderExcelOutDto;
import com.egoo.ticket.server.pojo.dto.WorkOrderSelectInputDto;
import com.egoo.ticket.server.pojo.entity.EwsUser;
import com.egoo.ticket.server.pojo.entity.WorkOrder;
import com.egoo.ticket.server.project.ProjectConstant;
import com.egoo.ticket.server.project.jincheng.JinChengExportDto;
import com.egoo.ticket.server.service.EripDataSynService;
import com.egoo.ticket.server.service.WorkOrderExcelService;
import com.egoo.ticket.server.service.WorkOrderService;
import com.egoo.ticket.server.utils.common.ConstantCode;
import com.egoo.ticket.server.utils.common.ExcelUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Donny_dong
 */
@Slf4j
@RestController
@RequestMapping(value = "/v1/workOrderExcelOutDto", produces = "application/json")
@Api(value = "工单导出管理",tags = "工单导出管理",description = "工单导出管理")
public class WorkOrderExcelController {

	@Autowired
	private WorkOrderExcelService workOrderExcelService;
	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private WorkOrderDao workOrderDao;
	@Autowired
	private EripDataSynService eripDataSynService;
	@Autowired
	private EwsUserDao ewsUserDao;
	@Value("${server.project-sign}")
	private String projectSign;

	//@ApiOperation(value = "Excel导出接口", notes = "Excel导出接口")
	//@RequestMapping(method = RequestMethod.POST, value = "/writeWithHead")
	//public void writeWithHead(@RequestBody WorkOrderExcelInput workOrderExcelInput,
    //                          HttpServletRequest request, HttpServletResponse response) {
	//	log.info("开始执行导出...");
	//	//根据条件查询导出的数据
	//	String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
	//	String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
	//	try {
	//		//获取满足导出条件的工单id
	//		List<String> workOrderIds = getWorkOrderIds(workOrderExcelInput, tenantId);
	//
	//		List exportDataList=null;
	//		int exportNum = 0;
	//		if (workOrderIds!=null && workOrderIds.size()>0) {
	//			// 获取并翻译导出的工单数据
	//			exportDataList= workOrderExcelService.selectByIdList(workOrderIds);
	//			exportNum = workOrderIds.size();
	//		}
	//		handleExportExcel(exportDataList,response);
	//		// 推送关键操作日志至工作台
	//		EwsUser ewsUser = ewsUserDao.selectById(userId);
	//		String content = ewsUser.getName()+"导出了"+exportNum+"条工单！";
	//		SysOptLogDto sysOptLogDto = new SysOptLogDto(userId,content,
	//				ConstantCode.SysOptLog.SERVICE_TYPE_EXPORT, content, ConstantCode.SysOptLog.STATUS_SUCESS,
	//				null,tenantId,ConstantCode.SysOptLog.OPT_MODULE_WORK_ORDER);
	//		eripDataSynService.recordSysOptLog(sysOptLogDto);
	//		log.info("导出完成！");
	//	} catch (Exception e) {
	//		log.error("工单导出异常："+e);
	//	}
	//}

	/**
	 * @Author: Donny_dong
	 * @Description: 导出处理
	 * @Param:
	 * @return:
	 * @Date: 2020/8/18
	 */
	private void handleExportExcel(List exportDataList,HttpServletResponse response) throws UnsupportedEncodingException {
		Map<String, List<? extends BaseRowModel>> map = new HashMap<>(2);
		Class excelClass = null;
		// 支持多sheet导出，一个map元素代表一个sheet
		if (ProjectConstant.ProjectSign.PRODUCT.equals(projectSign) || null == projectSign) {
			map.put("导出数据信息", (List<WorkOrderExcelOutDto>)exportDataList);
			excelClass = WorkOrderExcelOutDto.class;
		}else if (ProjectConstant.ProjectSign.JINCHNEG.equals(projectSign)){
			map.put("导出数据信息",(List<JinChengExportDto>)exportDataList);
			excelClass = JinChengExportDto.class;
		}
		ExcelUtil.createExcelStreamMutilByEaysExcel(response, map,
				ExcelTypeEnum.XLSX, System.currentTimeMillis()+".xlsx",
				excelClass);
	}

	/**
	 * TODO 获取满足导出条件的工单id
	 * @author: victor_tang
	 * @createtime: 2020/4/21 15:17
	 * @param workOrderExcelInput 1
	 * @param tenantId 2
	 * @return: java.utils.List<java.lang.String>
	 */
	private List<String> getWorkOrderIds(WorkOrderExcelInput workOrderExcelInput,String tenantId){
		//根据条件查询导出的数据
		if (!CollectionUtils.isEmpty(workOrderExcelInput.getWorkOrderIdList())) {
			return workOrderExcelInput.getWorkOrderIdList();
		} else {
			WorkOrderSelectInputDto workOrderSelectInputDto = workOrderExcelInput.getWorkOrderSelectInputDto();
			workOrderSelectInputDto.setTenantId(tenantId);
			// 处理查询sql
			String sql = handleExportSql(workOrderSelectInputDto);
			log.info("查询导出工单id的sql: {}", sql);
			List<String> workOrderIdList = new ArrayList<>();
			List<WorkOrder> workOrderList = workOrderDao.selectBySql(sql);
			if (workOrderList != null && workOrderList.size() > 0) {
				for (WorkOrder workOrder : workOrderList) {
					workOrderIdList.add(workOrder.getId());
				}
			}
			return workOrderIdList;
		}
	}

	/**
	 * TODO 拼接导出查询sql
	 *
	 * @param workOrderSelectInputDto 1
	 * @author: victor_tang
	 * @createtime: 2020/3/9 18:32
	 * @return: java.lang.String
	 */
	private String handleExportSql(WorkOrderSelectInputDto workOrderSelectInputDto) {
		// 拼接列表查询条件
		String sql = workOrderService.joinSqlContion(workOrderSelectInputDto);
		return sql.replace("select a.*," +"b.work_order_id,b.urge_count,b.redeploy_count,b.contact_work_order_id_str,b.is_time_out,b.session_id,b.external_work_order_id,b.work_order_monitor_id,b.merge_base_work_order_ids,b.is_recieve,b.sender,b.is_children ", "select a.id ");
	}


	/**
	 * @Description:
	 * @Author: xwy
	 * @Date: 2020/11/4 10:38
	 * @param workOrderExcelInput: 
	 * @param request: 
	 * @param response: 
	 * @return: void
	 **/
	@ApiOperation(value = "Excel导出接口", notes = "Excel导出接口")
	@RequestMapping(method = RequestMethod.POST, value = "/writeWithHead")
	public void writeWithDynamicHead(@RequestBody WorkOrderExcelInput workOrderExcelInput,
							  HttpServletRequest request, HttpServletResponse response) {
		log.info("开始执行导出...");
		Map<String,Object> dataMap= Maps.newHashMap();
		List<List<Object>> dataList= Lists.newArrayList();
		List<String> headsList=Lists.newArrayList();
		//根据条件查询导出的数据
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		try {
			//获取满足导出条件的工单id
			//参数 workOrderIdList如果传值 以传参为准 否则 需要根据workOrderSelectInputDto 参数查询获得工单id的List
			List<String> workOrderIds = getWorkOrderIds(workOrderExcelInput, tenantId);

			List exportDataList=null;
			int exportNum = 0;
			if (workOrderIds!=null && workOrderIds.size()>0) {
				// 获取并翻译导出的工单数据
				//先查询了work_order表获取相应的数据 进行过重新的组装
				 dataMap= workOrderExcelService.selectByIdListDynamic(workOrderIds,projectSign);
				 dataList= (List<List<Object>>) dataMap.get("dataList");
				 headsList= (List<String>) dataMap.get("heads");
				 exportNum = dataList.size();
			}

			ExcelUtil.ExcelStreamMutilByEaysExcel(response,headsList,dataList,System.currentTimeMillis()+".xlsx");
			// 推送关键操作日志至工作台
			EwsUser ewsUser = ewsUserDao.selectById(userId);
			String content = ewsUser.getName()+"导出了"+exportNum+"条工单！";
			SysOptLogDto sysOptLogDto = new SysOptLogDto(userId,content,
					ConstantCode.SysOptLog.SERVICE_TYPE_EXPORT, content, ConstantCode.SysOptLog.STATUS_SUCESS,
					null,tenantId,ConstantCode.SysOptLog.OPT_MODULE_WORK_ORDER);
			eripDataSynService.recordSysOptLog(sysOptLogDto);
			log.info("导出完成！");
		} catch (Exception e) {
			log.error("工单导出异常："+e);
		}
	}




}
